package com.wxyzz.cem.util;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson2.JSON;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;

import java.util.Date;

/**
 * @author xclhove
 */
public class TokenUtil {
    /**
     * 生成token
     */
    public static<FT, ST> String generate(FT firstAudience, ST secondAudience, String secret) {
        String firstJsonStr = JSON.toJSONString(firstAudience);
        String secondJsonStr = JSON.toJSONString(secondAudience);
        return JWT.create().withAudience(firstJsonStr, secondJsonStr)
                .withExpiresAt(DateUtil.offsetHour(new Date(), 24))
                .sign(Algorithm.HMAC256(secret));
    }
    
    /**
     * 获取token中的信息
     */
    public static <T> T getFirstAudience(String token, Class<T> returnType, int index) {
        try {
            String jsonStr = JWT.decode(token).getAudience().get(index);
            return JSON.parseObject(jsonStr, returnType);
        } catch (Exception exception) {
            return null;
        }
    }
    
    /**
     * 获取token中的信息
     */
    public static <T> T getFirstAudience(String token, Class<T> returnType) {
        return getFirstAudience(token, returnType, 0);
    }
    
    /**
     * 获取token中的信息
     */
    public static <T> T getSecondAudience(String token, Class<T> returnType) {
        return getFirstAudience(token, returnType, 1);
    }
    
    /**
     * 校验token
     */
    public static boolean validate(String token, String secret) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(secret);
            JWTVerifier verifier = JWT.require(algorithm).build();
            verifier.verify(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
